import Constants from "../Constants/Constants";

/**
 * 声音管理
 * created by Five on 2018-11-21 18:10:41
 */
export default class SoundHelper {

    private _sfxVolume: number = 1.0;
    private _bgmVolume: number = 1.0;

    private _runningbgm: number = -1;

    constructor() {
        this.init();
    }

    init() {
        let t;
        t = cc.sys.localStorage.getItem(Constants.LOC_BGMVOLUME);
        if (t != null && t != "")
            this._bgmVolume = parseFloat(t);

        t = cc.sys.localStorage.getItem(Constants.LOC_SFXVOLUME);
        if (t != null && t != "")
            this._sfxVolume = parseFloat(t);

        cc.systemEvent.on(cc.game.EVENT_HIDE, () => {
            cc.audioEngine.pauseAll();
        });
        cc.systemEvent.on(cc.game.EVENT_SHOW, () => {
            cc.audioEngine.resumeAll();
        });
    }

    private getUrl(url): string {
        return "sounds/" + url;
    }

    public PlayBGM(url: string, loop:boolean = true) {
        var audioUrl = this.getUrl(url);
        if (this._runningbgm >= 0) {
            cc.audioEngine.stop(this._runningbgm);
        }
        cc.loader.loadRes(audioUrl, cc.AudioClip, function (err, clip) {
            if (err || !clip) {
                console.error(`audioUrl=${audioUrl}, err=`, err);
                return;
            }
            this._runningbgm = cc.audioEngine.play(clip, loop, this._bgmVolume);
        }.bind(this));
    }

    public playSFX(url: string) {
        if (url == "")
            return;

        var audioUrl = this.getUrl(url);
        if (this._sfxVolume > 0) {
            cc.loader.loadRes(audioUrl, cc.AudioClip, function (err, clip) {
                if (err || !clip) {
                    console.error(`audioUrl=${audioUrl}, err=`, err);
                    return;
                }
                var audioId = cc.audioEngine.play(clip, false, this._sfxVolume);
            }.bind(this));
        }
    }

    public openBGM(){
        this.setBGMVolume(1);
    }

    public closeBGM(){
        this.setBGMVolume(0);
    }

    public openSFX(){
        this.setSFXVolume(1);
    }

    public closeSFX(){
        this.setSFXVolume(0);
    }

    public setSFXVolume(v) {
        if (this._sfxVolume != v) {
            this._sfxVolume = v;
        }
        cc.sys.localStorage.setItem(Constants.LOC_SFXVOLUME, v);
    }

    public setBGMVolume(v, force?) {
        if (this._runningbgm >= 0) {
            if (v > 0) {
                cc.audioEngine.resume(this._runningbgm);
            }
            else {
                cc.audioEngine.pause(this._runningbgm);
            }
        }
        if (this._bgmVolume != v || force) {
            this._bgmVolume = v;
            cc.audioEngine.setVolume(this._runningbgm, v);
        }
        cc.sys.localStorage.setItem(Constants.LOC_BGMVOLUME, v);
    }

    public pauseAll() {
        cc.audioEngine.pauseAll();
    }

    public resumeAll() {
        cc.audioEngine.resumeAll();
    }
}